package com.struts2.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.hibernate.HibernateUtil;
import com.paypal.PayPalResult;
import com.struts2.model.CartItem;
import com.struts2.model.Customer;
import com.struts2.model.Invoice;
import com.struts2.model.Invoice_item;
import com.struts2.model.Product_item;

public class PayPalService {

	@SuppressWarnings("deprecation")
	public void insertInvoice(PayPalResult result, List<CartItem> cart) throws ParseException{
		
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		Customer customer = new Customer();
		customer.setAddress(result.getAddress_name());
		//customer.setDob();
		customer.setEmail(result.getReceiver_email());
		//customer.setGender();
		customer.setName(result.getFirst_name() + "-" + result.getLast_name());
		customer.setPhone_number(12345678);
		session.save(customer);
		
		Invoice invoice = new Invoice();
		invoice.setCustomer(customer);
		//DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
		//Date date = df.parse(result.getPayment_date());
		Date date = new Date();
		date.getDate();
		invoice.setDate(date);
		invoice.setMailing_address(result.getAddress_name());
		invoice.setPayment_method("PayPal");
		invoice.setStatus("fail");
		session.save(invoice);
		
		if( cart != null ) {
			for (Iterator<CartItem> i = cart.listIterator(); i.hasNext();) {
				CartItem cCartItem = i.next();
				Invoice_item invoice_item = new Invoice_item();
				invoice_item.setInvoice(invoice);
				invoice_item.setQuantity(cCartItem.getCartItemQuantity());
				invoice_item.setPrice(cCartItem.getCartItemPrice());
				invoice_item.setProduct_item(getProduct_itemByCartItem(cCartItem));
				session.save(invoice_item);
			}
		}
		
		session.getTransaction().commit();
		session.close();
		
	}
		
	public Product_item getProduct_itemByCartItem(CartItem cartItem) {
			
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
			
		Criteria criteria = session.createCriteria(Product_item.class);
		criteria.add(Restrictions.eq("id", cartItem.getProductItemId()));
		
		Product_item product_item = (Product_item) criteria.list().get(0);
		
		session.getTransaction().commit();
		session.close();
			
		return product_item;
		
	}

}
